const { CustomErr, UnknowErr } = require('./code')
const { NODE_ENV } = require('../config/default')
const { APP_ENV } = require('../consts/system')
const { reportLog } = require('../util/log')
// 错误统一处理
const errHandler = (err, ctx) => {
  if (err instanceof CustomErr) {
    // CustomErr 里有 error这个方法
    const env = NODE_ENV || 'prod'
    if (env !== APP_ENV.DEV) {
      err.data = null
      delete err.stack
    }
    ctx.body = err.toString()
  } else {
    console.log(err, '<<< err')
    try {
      // 上报错误日志
      reportLog(JSON.stringify(err), ctx)
    } catch (err) {
      console.log(err, '<<< reportLog err')
    }

    // TOOD 记录日志
    ctx.body = UnknowErr.toString()
    // throw new Error(err)
  }
}

module.exports = errHandler
